package ph.com.gs3.formalistics.service.managers;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import ph.com.gs3.formalistics.model.communicators.MessagingCommunicatorModule;
import ph.com.gs3.formalistics.model.communicators.HttpCommunicatorModule.CommunicatorException;
import ph.com.gs3.formalistics.model.valueobjects.application.APIResponse;
import ph.com.gs3.formalistics.model.valueobjects.application.APIResponse.APIInvalidResponseException;
import ph.com.gs3.formalistics.model.valueobjects.business.Message;
import ph.com.gs3.formalistics.model.valueobjects.business.MessageThread;

public class MessagingManager {

	public static final String TAG = MessagingManager.class.getSimpleName();

	private MessagingCommunicatorModule messagingCommunicatorModule;

	public MessagingManager(MessagingCommunicatorModule messagingCommunicatorModule) {
		this.messagingCommunicatorModule = messagingCommunicatorModule;
	}

	public List<MessageThread> getCurrentUserThreadList() {

		List<MessageThread> threadList = new ArrayList<MessageThread>();

		try {
			APIResponse response = messagingCommunicatorModule.getCurrentUserThreadList();
			if (response.isOperationSuccessful()) {

				// throws JSONException
				JSONArray responseJSON = new JSONArray(response.getResults());
				for (int i = 0; i < responseJSON.length(); i++) {
					try {
						// throws JSONException
						MessageThread thread = MessageThread.createFromJSON(responseJSON
						        .getJSONObject(i));
						threadList.add(thread);

						// TODO: add persistence functionality here
					} catch (JSONException e) {
						// invalid server response
						e.printStackTrace();
					}
				}

			}

		} catch (CommunicatorException | APIInvalidResponseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// invalid server response
			e.printStackTrace();
		}

		return threadList;

	}

	public List<Message> getThreadMessages() {

		
		
		return null;
	}

}
